<?php

namespace app\hannel\command;

use app\business\model\RongcuiPotentialCustomerModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\Validate;

class Import extends Command
{
    protected function configure()
    {
        $this->addArgument('file_id', Argument::REQUIRED); //必传参数
        $this->setName('import_file')->setDescription('Command Test');
    }

    protected function execute(Input $input, Output $output)
    {
        $file_id = $input->getArgument('file_id');
        $files = db('import_list')->find($file_id);
        if ($files && $files['status'] == 0) {
            $result = db('import_list')->where([
                'id' => $file_id
            ])->update([
                'status' => 1
            ]);
            if($result){
                $file = CMF_ROOT.'public/upload/'.$files['filename'];
                try {
                    $objRead = new \PHPExcel_Reader_Excel2007();   //建立reader对象
                    if (!$objRead->canRead($file)) {
                        $objRead = new \PHPExcel_Reader_Excel5();
                        if (!$objRead->canRead($file)) {
                            $objRead = new \PHPExcel_Reader_CSV();
                            if (!$objRead->canRead($file)) {
                                db('import_list')->where([
                                    'id' => $file_id
                                ])->update([
                                    'status' => 3,
                                    'message' => '文件读取失败'
                                ]);
                                return;
                            }
                            $objRead->setInputEncoding('GBK');
                        }
                    }
                    $phpexcel = $objRead->load($file);
                    $result = $this->readexcel($phpexcel);

                    $success_count = 0;
                    $error_count = 0;
                    $time = time();
                    $potentialCustomerModel = new RongcuiPotentialCustomerModel();
                    $validate = new Validate();
                    foreach ($result as $item) {
                        $str = $item[3];
                        $type = 1;
                        if(strpos($str,'港币')) {
                            $type = 3;
                        }elseif(strpos($str,'港元')){
                            $type = 3;
                        }elseif(strpos($str,'美元')){
                            $type = 2;
                        }elseif(strpos($str,'日元')){
                            $type = 4;
                        }elseif(strpos($str,'欧元')){
                            $type = 5;
                        }elseif(strpos($str,'瑞士法郎')){
                            $type = 6;
                        }elseif(strpos($str,'新加坡元')){
                            $type = 7;
                        }

                        if(strpos($str,'万')) {
                            $registered_capital = floatval($str);
                        }else{
                            $registered_capital = floatval($str) / 10000;
                        }

                        $data = [
                            'company' => $item[0],
                            'corporation' => $item[1],
                            'regtime' => strtotime($item[2]),
                            'registered_capital' => $registered_capital,
                            'currency' => $type,
                            'address' => $item[4],
                            'email' => $item[5],
                            'phone' => $item[6],
                            'scope' => $item[7],
                            'remark' => $item[8],
                            'create_time' => $time,
                            'update_time' => $time,
                            'uid' => $files['uid'],
                        ];
                        $validate->rule([
                            'company' => 'require',
//                            'email' => 'unique:potential_customer',
                            'phone' => 'unique:potential_customer',
                        ]);
                        $validate->message([
                            'company.require' => '公司名称不能为空！',
//                            'email.unique' => '邮箱不能重复！',
                            'phone.unique' => '手机号不能重复！',
                        ]);
                        if($validate->check($data)){
                            $success_count++;
                            $potentialCustomerModel->insert($data);
                        }else{
                            $error_count++;
                        }
                    }
                    db('import_list')->where([
                        'id' => $file_id
                    ])->update([
                        'status' => 2,
                        'success_count' => $success_count,
                        'error_count' => $error_count,
                    ]);
                } catch (\Exception $e) {
                    db('import_list')->where([
                        'id' => $file_id
                    ])->update([
                        'status' => 3,
                        'message' => $e->getMessage()
                    ]);
                    return;
                }
            }
        }
    }

    /**
     * @param \PHPExcel $phpexcel
     * @return array
     */
    private function readexcel($phpexcel) {
        $objWorksheet = $phpexcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 2; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $cellValue = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                if($cellValue instanceof \PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }
                $excelData[$row][] = $cellValue;
            }
        }
        return $excelData;
    }
}